package com.billsystem.controller;

import com.billsystem.pojo.User;
import com.billsystem.service.UserService;
import com.billsystem.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;

    @PostMapping("insertUser")
    public String insertUser(@RequestBody User user){
        try {
            User bean = userService.queryUserByName(user.getName());
            if(bean != null){
                return "exist";
            }else{
                userService.insertUser(user);
                return "ok";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }

    @PostMapping("validateUser")
    public Object validateUser(@RequestBody User user, HttpSession session){
        try{
            User bean = userService.queryUserByName(user.getName());
            if(bean == null){
                return "noExist";
            }else{
                if(bean.getPassword().equals(user.getPassword())){
                    session.setAttribute("userId",bean.getId());
                    return Result.success();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "error";
    }

    @PutMapping("updateUser")
    public Object updateUser(@RequestBody User user){
        try{
            userService.update(user);
            return Result.success().setMessage("个人信息更新成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("error");
        }
    }

    @GetMapping("/quit")
    public Object quit(HttpSession session){
        try{
            session.removeAttribute("userId");
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("error");
        }
    }

    @Value("${user.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public Object uploadImage(@RequestParam(value="file",required=false) MultipartFile file) {
        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = null;
            if (originalFilename != null) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            //使用UUID重新生成文件名，防止文件被覆盖
            String fileName = UUID.randomUUID() + suffix;
            //创建一个目录对象
            File dir = new File(uploadPath);
            //判断文件是否存在
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 指定保存路径
            String filePath = uploadPath + "/" + fileName;
            // 保存文件到本地
            file.transferTo(new File(filePath));
            // 更新用户数据库
            int id = (int) session.getAttribute("userId");
            userService.updateUserImg(fileName, id);
            return Result.success(fileName).setMessage("头像更新成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("error");
        }
    }

}
